﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;

namespace WooCoo.DataPortal.Server.Hosts.WcfChannel
{
    /// <summary>
    /// WCF模式的服务端异常处理实现
    /// </summary>
    public class ServiceErrorHandler : IErrorHandler
    {
        public ServiceErrorHandler()
        {
        }

        #region IErrorHandler 成员
        /// <summary>
        /// 错误处理
        /// </summary>
        /// <param name="error"></param>
        /// <returns>本方法在Client终结点端执行.</returns>
        public bool HandleError(System.Exception error)
        {
            //throw error;
            return false;
        }
        /// <summary>
        /// 错误消息构造,该方法在服务端执行
        /// </summary>
        /// <param name="error"></param>
        /// <param name="version"></param>
        /// <param name="fault"></param>
        public void ProvideFault(System.Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (typeof(FaultException).IsInstanceOfType(error))
            {
                return;
            }
            try
            {
                fault = BuildFault(version, error);
            }
            catch (System.Exception ex)
            {
                fault = BuildFault(version, ex);
            }
        }

        private Message BuildFault(System.ServiceModel.Channels.MessageVersion version, System.Exception error)
        {
            ServiceExceptionDetail exceptionDetail = new ServiceExceptionDetail(error);
            FaultCode fc = FaultCode.CreateSenderFaultCode(ServiceExceptionDetail.FaultSubCodeName, ServiceExceptionDetail.FaultSubCodeNamespace);
            FaultException<ServiceExceptionDetail> fe = new FaultException<ServiceExceptionDetail>(exceptionDetail, new FaultReason(error.Message), fc, ServiceExceptionDetail.FaultAction);
            MessageFault msgfa = fe.CreateMessageFault();
            return Message.CreateMessage(version, msgfa, fe.Action);
        }
        #endregion
    }
}
